package com.woniu.user.service.Imp;

import com.woniu.common.CustomException.UserException;
import com.woniu.common.pojo.Order;
import com.woniu.common.pojo.Shops;
import com.woniu.common.pojo.User;
import com.woniu.common.vo.AjaxResult;
import com.woniu.user.mapper.OrderMapper;
import com.woniu.user.service.OrdersService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class OrdersServiceImp implements OrdersService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public List<Order> getOrder(User user) {
        //  清空redis
        redisTemplate.delete("order" + user.getUsername());
        if (user != null) {
            if (user.getId() == null) {
                throw new RuntimeException("用户信息不完整");
            }
            List<Order> orderList = (List<Order>) redisTemplate.opsForValue().get("order" + user.getUsername());
            if (orderList != null) {
                for (Order order : orderList) {
                    elasticsearchRestTemplate.save(order);
                }
                return orderList;
            }
            List<Order> orders = orderMapper.getOrder(user.getId());
            if (orders != null) {
                for (Order order : orders) {
                    elasticsearchRestTemplate.save(order);
                }
                redisTemplate.opsForValue().set("order" + user.getUsername(), orders);
            }
            return orders;
        }
        throw new RuntimeException("不好意思,参数有误");
    }


    @Override
    public void updateOrder(Order order) {
        if (order != null) {
            Integer i = orderMapper.updateOrder(order);
            if (i > 0) {
                elasticsearchRestTemplate.delete(order);
                return;
            }
            throw new UserException("不好意思,未知异常");
        }
        throw new RuntimeException("不好意思,参数有误");
    }

    @Override
    public void deleteOrder(Order order) {
        if (order != null) {
            Integer i = orderMapper.deleteOrder(order);
            if (i > 0) {
                redisTemplate.delete("order" + order.getShops().getSname() + "");
                return;
            }
            throw new UserException("不好意思,未知异常");
        }
        throw new RuntimeException("不好意思,参数有误");
    }

    @Override
    public void deleteOrders(Integer[] selectedOrderIds, Shops obj) {
        if (selectedOrderIds != null) {
            Integer i = orderMapper.deleteOrders(selectedOrderIds);
            if (i == selectedOrderIds.length) {
                redisTemplate.delete("order" + obj.getSname() + "");
                return;
            }
            throw new UserException("未知错误");
        }
        throw new UserException("不好意思,数据有误");
    }

    @Override
    public List<Order> getOrders(Order order) {
        NativeSearchQuery query = null;
        if (order == null) {
            throw new UserException("不好意思,输入有误");
        }
        if (order.getUser().getUsername() != null && !"".equals(order.getUser().getUsername()) && (order.getAddress() == null || "".equals(order.getAddress()))) {
            query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchQuery("user.username", order.getUser().getUsername())).build();
            //2. 查询
        } else if (order.getAddress() != null && !order.getAddress().isEmpty() && (order.getUser().getUsername() == null || order.getUser().getUsername().isEmpty())) {
            query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchQuery("address", order.getAddress())).build();
            // 2. 执行查询
        } else if (order.getAddress() != null && order.getUser().getUsername() != null) {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            List<QueryBuilder> mustList = boolQueryBuilder.must();
            mustList.add(QueryBuilders.matchQuery("user.username", order.getUser().getUsername()));
            mustList.add(QueryBuilders.matchQuery("address", order.getAddress()));
            query = new NativeSearchQueryBuilder()
                    .withQuery(boolQueryBuilder).build();
        }
        //2. 查询
        SearchHits<Order> searchHits = elasticsearchRestTemplate.search(query, Order.class);
        //3. 迭代或者遍历
        System.out.println("总命令中数：" + searchHits.getTotalHits());
        searchHits.forEach(searchHit -> System.out.println(searchHit.getContent()));
        List<SearchHit<Order>> list = searchHits.toList();
        List<Order> orders = new ArrayList<>();
        for (SearchHit<Order> searchHit : list) {
            orders.add(searchHit.getContent());
        }
        return orders;
    }




    private String encryptUUID(String uuid) {
        // 实现UUID加密逻辑
        return uuid; // 示例返回原始UUID
    }

    @Override
    public Integer addOrder(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            return 0; // 返回0表示失败
        }
        Map<Integer, List<Order>> ordersByShop = new HashMap<>();
        for (Order order : orders) {
            ordersByShop.computeIfAbsent(order.getShops().getSid(), k -> new ArrayList<>()).add(order);
        }
        ArrayList<Order> orders1 = new ArrayList<>();
        for (Map.Entry<Integer, List<Order>> entry : ordersByShop.entrySet()) {
            String encryptedUUID = encryptUUID(UUID.randomUUID().toString());
            List<Order> shopOrders = entry.getValue();
            // 为当前商家的每个商品创建订单
            for (Order shopOrder : shopOrders) {
                shopOrder.setOid(encryptedUUID);
                orders1.add(shopOrder);
            }
        }

        int successCount = 0;
        for (Order order : orders1) {
            int result = orderMapper.addOrder(order);
            if (result > 0) {
                successCount++;
            }
        }
        return successCount; // 返回成功添加的订单数量
    }



    @Transactional
    @Override
    public AjaxResult updateRefundStatus(String oid, String comment) {
        if (oid == null || comment == null) {
            return AjaxResult.error("订单ID和退款理由不能为空");
        }

        int updated = orderMapper.updateRefundStatus(oid, comment);
        if (updated > 0) {
            return AjaxResult.success("退款申请提交成功");
        } else {
            return AjaxResult.error("退款申请提交失败");
        }
    }

}
